package com.ljh.onlinetest.controller.admin;

import com.github.pagehelper.PageInfo;
import com.ljh.onlinetest.base.BaseApiController;
import com.ljh.onlinetest.base.RestResponse;
import com.ljh.onlinetest.domain.Subject;
import com.ljh.onlinetest.service.SubjectService;
import com.ljh.onlinetest.utils.PageInfoHelper;
import com.ljh.onlinetest.viewmodel.admin.subject.SubjectEditVM;
import com.ljh.onlinetest.viewmodel.admin.subject.SubjectPageRequestVM;
import com.ljh.onlinetest.viewmodel.admin.subject.SubjectResponseVM;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author ljh
 * @ClassName EducationController.java
 * @createTime 2022年01月17日
 */
@RestController("AdminEducationController")
@RequestMapping("/api/admin/education/subject")
public class EducationController extends BaseApiController {

    private SubjectService subjectService;

    @Autowired
    public EducationController(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @PostMapping("/list")
    public RestResponse<List<Subject>> getSubjectList(){
        return RestResponse.ok(subjectService.allSubject());
    }

    @PostMapping("/page")
    public RestResponse<PageInfo<SubjectResponseVM>> listPage(@RequestBody SubjectPageRequestVM subjectPageRequestVM) {
        PageInfo<Subject> subjectPageInfo = subjectService.listPage(subjectPageRequestVM);
        PageInfo<SubjectResponseVM> subjectResponseVMPageInfo = PageInfoHelper.copyMap(subjectPageInfo,e -> modelMapper.map(e,SubjectResponseVM.class));
        return RestResponse.ok(subjectResponseVMPageInfo);
    }

    @PostMapping("/edit")
    public RestResponse editSubject(@RequestBody @Valid SubjectEditVM subjectEditVM){
        Subject subject = modelMapper.map(subjectEditVM, Subject.class);
        if (subject.getId() == null) { //create
            subject.setDeleted(false);
            subjectService.insertByFilter(subject);
        }else {
            subjectService.updateByIdFilter(subject);
        }
        return RestResponse.ok();
    }

    @PostMapping("/select/{id}")
    public RestResponse<SubjectResponseVM> getById(@PathVariable Integer id){
        Subject subject = subjectService.selectById(id);
        SubjectResponseVM subjectResponseVM = modelMapper.map(subject, SubjectResponseVM.class);
        return RestResponse.ok(subjectResponseVM);
    }

    @PostMapping("/delete/{id}")
    public RestResponse deleteById(@PathVariable Integer id){
        Subject subject = subjectService.selectById(id);
        subject.setDeleted(true);
        subjectService.updateByIdFilter(subject);
        return RestResponse.ok();
    }
}
